var JSBoot = {};
var Args = [];
(function(args) {

	JSBoot.args = args;

	JSBoot.pool = {};

	var beanMap = JSBoot.pool;

	var buildComponent = function(definition) {
		beanMap[definition.id] = definition;
	}

	var lasyLoadComponentRefs = function(definition) {
		if(definition.refs) {
			for(var key in definition.refs) {
				var obj = definition.refs[key];
				if(obj === undefined || obj == null) {
					definition.refs[key] = beanMap[key];
				}
			}
		}
	}

	JSBoot.component = function(definition) {
		buildComponent(definition);
	};

	JSBoot.service = function(definition) {
		buildComponent(definition);
	};

	JSBoot.repository = function(definition) {
		buildComponent(definition);
	};

	JSBoot.context = function() {

	};

	JSBoot.init = function(args) {
		if(JSBoot.loadStorage && typeof JSBoot.loadStorage === "function") {
			JSBoot.loadStorage(args);
		};
		if(JSBoot.loadWebSql && typeof JSBoot.loadWebSql === "function") {
			JSBoot.loadWebSql(args);
		};
	};

	JSBoot.run = function() {
		//初始化模块
		JSBoot.init(JSBoot.args);
		//装载
		for(var key in beanMap) {
			var bean = beanMap[key];
			lasyLoadComponentRefs(bean);
			if(beanMap[key].init) {
				beanMap[key].init();
			}
		}
		return JSBoot.context;
	}

	JSBoot.context.get = function(id) {
		if(beanMap[id]) {
			lasyLoadComponentRefs(beanMap[id]);
			return beanMap[id];
		}
		return null;
	};

	JSBoot.define = function() {
		if(arguments.length == 1) {
			var obj = arguments[0];
			if(typeof obj === "function") {
				return JSBoot.component(new obj());
			}
			if(typeof obj === "string") {
				return JSBoot.component(eval(obj));
			}
			if(typeof obj) {
				return JSBoot.component(obj);
			}
		}
		if(arguments.length == 2) {
			var id = arguments[0];
			var obj = arguments[1];
			if(typeof obj === "function") {
				var res = new obj();
				res.id = id;
				return JSBoot.component(res);
			}
			if(typeof obj === "string") {
				var res = eval(obj);
				res.id = id;
				return JSBoot.component(res);
			}
			if(typeof obj) {
				obj.id = id;
				return JSBoot.component(obj);
			}
		}

		if(arguments.length == 3) {
			var id = arguments[0];
			var refs = arguments[1];
			var obj = arguments[2];

			var init = function(obj) {
				obj.refs = {};
				for(var index in refs) {
					var name = refs[index];
					obj.refs[name] = null;
				}
			}

			if(typeof obj === "function") {
				var res = new obj();
				res.id = id;
				res.refs = refs;
				init(res);
				return JSBoot.component(res);
			}
			if(typeof obj === "string") {
				var res = eval(obj);
				res.id = id;
				init(res);
				return JSBoot.component(res);
			}
			if(typeof obj) {
				obj.id = id;
				init(res);
				return JSBoot.component(obj);
			}
		}
	}

}(Args));